
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const mongoPath = require('./config/default').mongodb

const dbs = {Blog:'', Tag: '', Test: ''}
const db = mongoose.connection
mongoose.connect(mongoPath)
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function() {
  console.log('database is connected!')

  // 初始化test表
  const testSchema = mongoose.Schema({
    name: String,
  })
  dbs.Test = mongoose.model('Test', testSchema) 

  // 初始化blog表
  const blogSchema = mongoose.Schema({
    title: String,
    content: String,
    tag: [{type: Schema.Types.ObjectId, ref: 'Tag'}],
    isPublished: Boolean,
    time: Number,
    href: String
  })
  dbs.Blog = mongoose.model('Blog', blogSchema)

  // 初始化tag表
  const tagSchema = mongoose.Schema({
    name: String,
    blog: [{type: Schema.Types.ObjectId, ref:'Blog'}]
  })
  dbs.Tag = mongoose.model('Tag', tagSchema)
})

module.exports = dbs